package com.babarus.netmonitor;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class DevicePanel extends Activity {

	private static final String TAG = null;
	GlobalState globalAppData;
	TextView _deviceAddresElement ;
	ToggleButton _connectState, _led1Input, _buttonInput; 
	ProgressBar _progresBar;
	int deviceId;
	String deviceIdentifier;
	EditText _temperaturaInput;
	EditText _potInput;
	SeekBar _connectionSpeed ;
	CheckBox _actualizareContinuua ;
	Handler continousConnedctionHandler = new Handler();
	Thread  continousThread ;
	boolean activeThreadFlag = true;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_panel_interface);
		globalAppData = ((GlobalState) getApplicationContext());
		_deviceAddresElement = (TextView) findViewById(R.id.deviceAddress);
		_connectState = (ToggleButton) findViewById(R.id.connectState);
		_led1Input = (ToggleButton) findViewById(R.id.led1Input);
		_buttonInput = (ToggleButton) findViewById(R.id.buttonInput);
		_progresBar = (ProgressBar) findViewById(R.id.progressBar1);

		_temperaturaInput = ((EditText)findViewById(R.id.temperaturaInput));
		_potInput = ((EditText)findViewById(R.id.potentiometruInput));
		_connectionSpeed = (SeekBar)findViewById(R.id.requestSpeed);
		_actualizareContinuua = (CheckBox)findViewById(R.id.actualizareContinuua);
		
		// Show the Up button in the action bar.
		
		Intent parentIntent = getIntent(); 
		deviceId = parentIntent.getIntExtra("deviceId", 0);		
		
		deviceIdentifier = globalAppData.getDeviceById(deviceId);
		_deviceAddresElement.setText(deviceIdentifier);

		connectionTest(deviceIdentifier);
		
		Button btn1 = (Button) findViewById(R.id.button1);
		btn1.setOnClickListener(new OnClickListener() {
		    	@Override
				public void onClick(View arg0) {
		            activeThreadFlag = false;
		            stopThread(continousThread);
		            finish();
				}
	    });		
		
		createRealTimeUpdate();
		

	}

	public void createRealTimeUpdate(){
		continousThread = new Thread(new Runnable() {
		        @Override
		        public void run() {
		        	int threadSpeed;
		            while (activeThreadFlag &&  _actualizareContinuua.isChecked() ) {
		            	threadSpeed = _connectionSpeed.getProgress();
		            	if(threadSpeed < 5){
		            		threadSpeed = 5;		            	
		            	}
		            	Log.i("hread speed", ""+threadSpeed);
		                try {
		                    Thread.sleep(threadSpeed*100);
		                    if(!activeThreadFlag || _actualizareContinuua.isChecked() == false ){ break; }
		                    continousConnedctionHandler.post(new Runnable() {

		                        @Override
		                        public void run() {
		                        	connectionTest(deviceIdentifier);	
		                        }
		                    });
		                } catch (Exception e) {

		                }
		            }
		        }
		});		
		continousThread.start();		
	}
	
	
	public void clickedLedTogle(View view){
		connectionTest("http://192.168.0.199/leds.cgi?led=1");
		
	}
	
	public void coonectButtonToggled(View view){
		boolean on = ((ToggleButton) view).isChecked();
		if (on == true) {
			connectionTest(deviceIdentifier);
            activeThreadFlag = false;
            stopThread(continousThread);
            activeThreadFlag = true;
			createRealTimeUpdate();
		} else {
			resetDeviceData();
            activeThreadFlag = false;
            stopThread(continousThread);
			
		}		
	}
	
	public void refrensDeviceData(PicWebModel currentDeviceState){
		if(currentDeviceState.online == true){
			_connectState.setVisibility(View.VISIBLE);
			_connectState.setChecked(true);
			_progresBar.setVisibility(View.INVISIBLE);
		} else {
			_connectState.setChecked(false);
			_connectState.setVisibility(View.VISIBLE);
			_progresBar.setVisibility(View.INVISIBLE);
			resetDeviceData();
			return ;			
		}
		
		String gradeSign = new String(new char[] { 176 });
		_temperaturaInput.setText(""+currentDeviceState.temp0+""+gradeSign+"C");
		
		_potInput.setText(""+currentDeviceState.pot0);
		
		_led1Input.setChecked(currentDeviceState.led1);
		
		_buttonInput.setChecked(currentDeviceState.btn0);
		_deviceAddresElement.setText(deviceIdentifier);
		
	}
	public void resetDeviceData(){
		_connectState.setChecked(false);
		_potInput.setText("");
		_temperaturaInput.setText("");
		_deviceAddresElement.setText("Deconectat");
		
		_led1Input.setChecked(false);
		_buttonInput.setChecked(false);
				
		
	}

	
	
	
    public void connectionTest(String deviceAddress){
        Intent intent = new Intent(this, ConnectionService.class);
        // Create a new Messenger for the communication back
        
        Messenger messenger = new Messenger(handler);
        intent.putExtra("MESSENGER", messenger);
        intent.putExtra("command", Configs.commands.TEST_BOARD_CONNECTION.getCode() );
        intent.putExtra("deviceAddress", deviceAddress);
        startService(intent);    	    	 
        
     }	
	
	
	
	
	
	
	
	
	
    private Handler handler = new Handler() {
        public void handleMessage(Message message) {
        	final Bundle bundle = message.getData();

        	String deviceResponce = bundle.getString("requestContent");
        	
        	switch(1){
	        	  case 1:{
	        		  ParseResponce parser = new ParseResponce(deviceResponce,getApplicationContext());
	        		  PicWebModel currentDeviceState = parser.parseXML();
	        		  
	        		  refrensDeviceData(currentDeviceState);
	        		  
	        		  break;
	        	  }
	    	}	
        };
    };

    
    private synchronized void stopThread(Thread theThread)
    {
        if (theThread != null)
        {
            theThread = null;
        }
    }
    
}
